#include "qtch/db/sqlite.h"
#include "qtch/log.h"

qtch::Logger::ptr logger = QTCH_LOG_NAME("test");
void test_sqlite3(){

    std::string db_path = "/home/qiu/UEIMHttpServer/qtch/temp/test.db";
    if(!qtch::FSUtil::Unlink(db_path,false)){
        QTCH_LOG_ERROR(logger) << "remove db path:" << db_path << " faile";
        return;
    }
    qtch::SQLite3Mgr::GetInstance()->registerSQLite3("test",db_path);
    qtch::SQLite3::ptr db_ptr = qtch::SQLite3Mgr::GetInstance()->get("test");
    if(!db_ptr){
        QTCH_LOG_ERROR(logger) << "connect sqlite faile";
        return;
    }
    QTCH_LOG_INFO(logger) << "connect sqlite success";
    std::string create_table_sql = "CREATE TABLE COMPANY("  \
         "ID INT PRIMARY KEY     NOT NULL," \
         "NAME           TEXT    NOT NULL," \
         "AGE            INT     NOT NULL," \
         "ADDRESS        CHAR(50)," \
         "SALARY         REAL );";
    if(!db_ptr->execute(create_table_sql)){
        QTCH_LOG_ERROR(logger) << "execute " << create_table_sql << " faile, error:" << db_ptr->getError() << " errstr:" << db_ptr->getErrStr();
        return;
    }
    QTCH_LOG_INFO(logger) << "create sqlite table success";
    std::string install_data_sql = "INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) "  \
         "VALUES (1, 'Paul', 32, 'California', 20000.00 )," \
         "(2, 'Allen', 25, 'Texas', 15000.00 ),"     \
         "(3, 'Teddy', 23, 'Norway', 20000.00 )," \
         "(4, 'Mark', 25, 'Rich-Mond ', 65000.00 );";

    if(!db_ptr->execute(install_data_sql)){
        QTCH_LOG_ERROR(logger) << "execute " << install_data_sql << " faile, error:" << db_ptr->getError() << " errstr:" << db_ptr->getErrStr();
        return;
    }
    QTCH_LOG_INFO(logger) << "insert value success";
    
    std::string select_data_sql = "select * from COMPANY;";
    qtch::ISQLData::ptr data_ptr = db_ptr->query(select_data_sql);
    if(!data_ptr){
        QTCH_LOG_ERROR(logger) << "query " << select_data_sql << " faile, error:" << db_ptr->getError() << " errstr:" << db_ptr->getErrStr();
        return;
    }
    QTCH_LOG_INFO(logger) << "select count:" << data_ptr->getDataCount();
    QTCH_LOG_INFO(logger) << "select column:" << data_ptr->getColumnCount();
    for(int i=0;i<data_ptr->getColumnCount();++i){
        std::cout << data_ptr->getColumnName(i) << "\t";
    }
    std::cout << "\n";
    while(data_ptr->next()){
        for(int i=0;i<data_ptr->getColumnCount();++i){
            std::cout << data_ptr->getString(i) << "\t";
        }
        std::cout << "\n";
    }

    
}


int main(){
    test_sqlite3();
}